﻿using System;
using System.Collections.Generic;

namespace Host
{
	public class CallDescriptionHttpHelper : IComponents
	{
		public CallDescriptionHttpHelper()
		{
		}

		public override void OnEnterEnd()
		{
			base.OnEnterEnd();

			var httpservercomponents = GetSameGropComponents<HttpServerComponents>("HttpServerComponents");
			TAssert.Assert(httpservercomponents != null, "CM2CDCHttpHelper Rely HttpServerComponents");

			var calldescriptioncomponents = GetSameGropComponents<CallDescriptionComponents>("CallDescriptionComponents");
			TAssert.Assert(calldescriptioncomponents != null, "CM2CDCHttpHelper Rely CallDescriptionComponents");

			foreach (var item in calldescriptioncomponents.GetAllCallInfo())
			{
				httpservercomponents.RouteData.RegisterRouteData(item.Key, (context) =>
				{
					Dictionary<string, object> query_map = new Dictionary<string, object>();
					foreach (var query_item in context.Request.QueryString.AllKeys)
					{
						query_map.Add(query_item, context.Request.QueryString[query_item]);
					}

					object obj = item.Value(query_map);

					if (obj == null)
						return string.Empty;

					if (obj is string)
						return obj as string;

					return LitJson.JsonMapper.ToJson(obj);
				});
			}

			httpservercomponents.RouteData.RegisterRouteData("", (context) =>
			{
				string html_string = "";

				html_string += "<!DOCTYPE html>";
				html_string += "<html>";
				html_string += "<head>";
				html_string += "	<title>The Host Project</title>";
				html_string += "</head>";
				html_string += "<body>";
				html_string += "<ul>";
				foreach (var item in calldescriptioncomponents.GetAllCallInfo())
				{
					html_string += "	<li><a href=\"" + item.Key + "\">" + item.Key + "</a></li>";
				}
				html_string += "</ul>";
				html_string += "</body>";
				html_string += "</html>";

				return html_string;
			});
		}
	}
}
